﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Dukou.Extensions
{
    public static class EnumExtension
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="enum"></param>
        /// <returns></returns>
        public static string GetDescription(this Enum @enum)
        {
            if (@enum == null)
            {
                return string.Empty;
            }

            Type enumType = @enum.GetType();
            string stringValue = @enum.ToString();

            FieldInfo fieldInfo = enumType.GetField(stringValue, BindingFlags.Public | BindingFlags.Static);
            if (fieldInfo == null)
            {
                return stringValue;
            }

            object[] attributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
            if (attributes.Length == 0)
            {
                return stringValue;
            }
            else
            {
                DescriptionAttribute description = attributes[0] as DescriptionAttribute;
                return description.Description;
            }
        }
    }
}
